/**
 * Created by wushanxin on 14-3-20.
 */



var config = require('../config');
var log = require('../lib/log');
var RUtil = require('./dataformatUtil');
var login = require('./login');
var crypto = require('crypto');
var virapinfo = require('../models/virapinfo');
var customerinfo = require('../models/customerinfo');
var customerlog = require('../models/customerlog');

exports.process = function(request, response){
    var retdata= RUtil.AP_COM();
    var info ='';
    request.addListener('data', function(chunk){
        info += chunk;
    }).addListener('end', function(){
            //根据action判断类型
            try{
                console.log("接收AP消息："+info);
                info = JSON.parse(info);
                info = info.apCom;
                var retFlag=0;
                var reason='';
                var action=info.apComHead.action;

                var ssid="";
                var passUrl='*.weibo.com||*.qq.com';
                var desKey="xsw";
                var vnoId="";//虚拟运营商标示使用viruser的userid

                //判断设备是否合法
                if(RUtil.checkVaild(info)==1)
                    return;

                switch(action)
                {
                    case "reg":
                    case "init":

                        virapinfo.selectAPWiFiWithAPMac(info.apComHead.apMac, function(error,results) {
                            if((error)!== null)
                            {
                                // 数据库异常
                                retFlag=1;
                                reason="system fault:errno("+error.errno+")";
                            } else if(results.length <= 0) {
                                // 不存在，直接响应页面
                                retFlag=1;
                                reason="ap does not exist.";
                            } else {
                                //存在数据更新virapinfo的字段状态为已注册
                                var apinfo=RUtil.ap_info(request);
                                apinfo.apmac=info.apComHead.apMac;
                                apinfo.apflag=1; //已注册
                                if(action=="init")
                                    apinfo.apflag=2; //已初始化
                                retFlag=0;
                                vnoId=results[0].wifiid;

                                ssid=results[0].apname;
                                duration=results[0].wifiauthhour;
                                traffic=-99;
                                rate=results[0].wifiauthbrand;


                                retdata.apComRet.apComRetCont.vnoId=vnoId;
                                retdata.apComRet.apComRetCont.ssid=results[0].wifissid;
                                retdata.apComRet.apComRetCont.passUrl=results[0].wifipassdomain;
                                retdata.apComRet.apComRetCont.desKey=desKey;
                                retdata.apComRet.apComRetCont.rate=rate;
                                retdata.apComRet.apComRetCont.traffic=traffic;
                                retdata.apComRet.apComRetCont.duration=duration;
                                if(results[0].groupenable==1)
                                {
                                    //retdata.apComRet.apComRetCont.groupenable=results[0].groupenable;
                                    retdata.apComRet.apComRetCont.devid=results[0].devid;
                                    retdata.apComRet.apComRetCont.group=results[0].groupidforssid;
                                }
                                /*
                                else
                                {
                                    retdata.apComRet.apComRetCont.groupenable=0;
                                }*/

                                if(results[0].apflag==0)
                                    virapinfo.updateapflag(apinfo, function(error,results) { });

                            }
                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                            retdata.apComRet.apComRetHead.reason=reason;


                            console.log("响应消息："+JSON.stringify(retdata));
                            response.send(JSON.stringify(retdata));
                        });
                        break;
                    case "access":

                        var duration=0;
                        var traffic=-99;
                        var rate=0;

                        virapinfo.selectAPWiFiWithAPMac(info.apComHead.apMac, function(error,results) {
                            if((error)!== null)
                            {
                                // 数据库异常
                                retFlag=1;
                                reason="system fault:errno("+error.errno+")";
                            } else if(results.length <= 0) {
                                // 不存在，直接响应页面
                                retFlag=1;
                                reason="ap does not exist.";
                            } else {
                                //存在数据
                                retFlag=0;
                                duration=results[0].wifiauthhour;
                                traffic=-99;
                                rate=results[0].wifiauthbrand;
                                vnoId=results[0].wifiid;
                                ssid=results[0].wifissid;
                            }
                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                            retdata.apComRet.apComRetHead.reason=reason;

                            retdata.apComRet.apComRetCont.rate=rate;
                            retdata.apComRet.apComRetCont.traffic=traffic;
                            retdata.apComRet.apComRetCont.duration=duration;

                            console.log("响应消息："+JSON.stringify(retdata));
                            response.send(JSON.stringify(retdata));
                        });
                        break;
                    case "online":

                        //online则更新 customerlog表
                        //根据上传的sessionId解析出customerid

                        var customerlogdata= RUtil.customerlogdata();
                        var customerid=info.apComCont.sessionId.split('_')[1];
                        customerlogdata.customerid=customerid;
                        customerlogdata.logauthtype=0;
                        customerlogdata.logcustip=info.apComCont.ip;
                        customerlogdata.logcustmac=info.apComCont.mac;
                        customerlogdata.logcurrentflow=0;
                        customerlogdata.logcurrenttime=0;
                        customerlogdata.logupdate=new Date();
                        customerlogdata.logdowndate=null;
                        customerlogdata.sessionid=info.apComCont.sessionId;
                        customerlog.insert(customerlogdata, function(error,results) {
                            if((error)!== null)
                            {
                                // 数据库异常
                                retFlag=1;
                                reason="system fault:errno("+error.errno+")";
                            } else if(results.length <= 0) {
                                // 不存在，直接响应页面
                                retFlag=1;
                                reason="user does not exist.";
                            } else {
                                //插入成功
                                retFlag=0;
                            }
                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                            retdata.apComRet.apComRetHead.reason=reason;

                            console.log("响应消息："+JSON.stringify(retdata));
                            response.send(JSON.stringify(retdata));
                        });
                        break;
                    case "counters":

                        var customerlogdata= RUtil.customerlogdata();
                        var customerid=info.apComCont.sessionId.split('_')[1];
                        customerlogdata.customerid=customerid;
                        customerlogdata.logauthtype=0;
                        customerlogdata.logcustip=info.apComCont.ip;
                        customerlogdata.logcustmac=info.apComCont.mac;
                        customerlogdata.logcurrentflow=(info.apComCont.downstream+info.apComCont.upstream)/1024;
                        customerlogdata.logcurrenttime=info.apComCont.duration;
                        //customerlogdata.logupdate=new Date();
                        customerlogdata.logdowndate=null;
                        customerlog.update(customerlogdata, function(error,results) {
                            if((error)!== null)
                            {
                                // 数据库异常
                                retFlag=1;
                                reason="system fault:errno("+error.errno+")";
                            } else if(results.length <= 0) {
                                // 不存在，直接响应页面
                                retFlag=1;
                                reason="user does not exist.";
                            } else {
                                //插入成功
                                retFlag=0;
                                customerinfo.updateCounters(customerlogdata, function(error,results) {});
                            }
                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                            retdata.apComRet.apComRetHead.reason=reason;
                            retdata.apComRet.apComRetCont.onlineState="online";

                            console.log("响应消息："+JSON.stringify(retdata));
                            response.send(JSON.stringify(retdata));
                        });
                        break;
                    case "offline":

                        var customerlogdata= RUtil.customerlogdata();
                        var customerid=info.apComCont.sessionId.split('_')[1];
                        console.log("===========offline===========customerid:"+customerid);
                        customerlogdata.customerid=customerid;
                        customerlogdata.logauthtype=0;
                        customerlogdata.logcustip=info.apComCont.ip;
                        customerlogdata.logcustmac=info.apComCont.mac;
                        customerlogdata.logcurrentflow=(info.apComCont.downstream+info.apComCont.upstream)/1024;
                        customerlogdata.logcurrenttime=info.apComCont.duration;
                        //customerlogdata.logupdate=new Date();
                        customerlogdata.logdowndate=new Date();

                        //同时要更新customerinfo表，如果用户在另外一个ap上还在线就不能下线customerinfo表
                        var whereclause={apmac:info.apComHead.apMac,wlanusermac:info.apComCont.mac};
                        customerinfo.updateOffline(whereclause, function(error,results) {});

                        customerlog.updateOffline(customerlogdata, function(error,results) {
                            if((error)!== null)
                            {
                                // 数据库异常
                                retFlag=1;
                                reason="system fault:errno("+error.errno+")";
                            } else if(results.length <= 0) {
                                // 不存在，直接响应页面
                                retFlag=1;
                                reason="user does not exist.";
                            } else {
                                retFlag=0;
                            }
                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                            retdata.apComRet.apComRetHead.reason=reason;

                            console.log("响应消息："+JSON.stringify(retdata));
                            response.send(JSON.stringify(retdata));
                        });
                        break;

                    case "passthrough":
                        {
                            var whereclause={apmac:info.apComHead.apMac,usermac:info.apComCont.mac};
                            virapinfo.selectForPassthrough(whereclause, function(error,results) {
                                console.log("json passthrough +results.length:"+results.length);
                                if((error)!== null)
                                {
                                    // 数据库异常
                                    retFlag=1;
                                    reason="system fault:errno("+error.errno+")";

                                    retdata.apComRet.apComRetHead.retFlag=retFlag;
                                    retdata.apComRet.apComRetHead.reason=reason;
                                    console.log("响应消息："+JSON.stringify(retdata));
                                    response.send(JSON.stringify(retdata));
                                    return;
                                } else if(results.length <= 0) {
                                    // 不存在，直接响应页面
                                    retFlag=1;
                                    reason="the customer did not access network in the same group.";

                                    retdata.apComRet.apComRetHead.retFlag=retFlag;
                                    retdata.apComRet.apComRetHead.reason=reason;
                                    console.log("响应消息："+JSON.stringify(retdata));
                                    response.send(JSON.stringify(retdata));
                                    return;
                                }
                                else {
                                    //存在数据
                                    retFlag=0;
                                    duration=results[0].wifiauthhour;
                                    traffic=-99;
                                    rate=results[0].wifiauthbrand;
                                    //同时往customerlog表中新增一条记录
                                    var customerlogdata= RUtil.customerlogdata();
                                    //

                                    customerinfo.selectCustExists(whereclause, function(error,results) {
                                        var adurl="";
                                        if((error)!== null)
                                        {
                                            // 数据库异常
                                            reason="system fault:errno("+error.errno+")";
                                            retFlag=1;

                                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                                            retdata.apComRet.apComRetHead.reason=reason;
                                            console.log("响应消息："+JSON.stringify(retdata));
                                            response.send(JSON.stringify(retdata));
                                            return;
                                        }
                                        else if(results.length <= 0)
                                        {
                                            reason="customer does not exists.";
                                            retFlag=1;

                                            retdata.apComRet.apComRetHead.retFlag=retFlag;
                                            retdata.apComRet.apComRetHead.reason=reason;
                                            console.log("响应消息："+JSON.stringify(retdata));
                                            response.send(JSON.stringify(retdata));
                                            return;
                                        }
                                        else
                                        {
                                            var sessid=Math.floor(Math.random()*(100000))+"";
                                            var newsessionid=crypto.createHash('md5').update(sessid).digest('hex')+"_"+results[0].customerid;
                                            customerlogdata.customerid=results[0].customerid;
                                            customerlogdata.logauthtype=0;
                                            customerlogdata.logcustip=info.apComCont.ip;
                                            customerlogdata.logcustmac=info.apComCont.mac;
                                            customerlogdata.logcurrentflow=0;
                                            customerlogdata.logcurrenttime=0;
                                            customerlogdata.logupdate=new Date();
                                            customerlogdata.logdowndate=null;
                                            customerlogdata.sessionid=newsessionid;
                                            customerlog.insert(customerlogdata, function(error,results) {
                                                if((error)!== null)
                                                {
                                                    // 数据库异常
                                                    retFlag=1;
                                                    reason="system fault:errno("+error.errno+")";

                                                    retdata.apComRet.apComRetHead.retFlag=retFlag;
                                                    retdata.apComRet.apComRetHead.reason=reason;
                                                    console.log("响应消息："+JSON.stringify(retdata));
                                                    response.send(JSON.stringify(retdata));
                                                    return;
                                                } else if(results.length <= 0) {
                                                    // 不存在，直接响应页面
                                                    retFlag=1;
                                                    reason="user does not exist.";

                                                    retdata.apComRet.apComRetHead.retFlag=retFlag;
                                                    retdata.apComRet.apComRetHead.reason=reason;
                                                    console.log("响应消息："+JSON.stringify(retdata));
                                                    response.send(JSON.stringify(retdata));
                                                    return;
                                                } else {
                                                    //插入成功
                                                    retFlag=0;

                                                    retdata.apComRet.apComRetHead.retFlag=retFlag;
                                                    retdata.apComRet.apComRetHead.reason=reason;
                                                    retdata.apComRet.apComRetCont.sessionId=newsessionid;

                                                    retdata.apComRet.apComRetCont.rate=rate;
                                                    retdata.apComRet.apComRetCont.traffic=traffic;
                                                    retdata.apComRet.apComRetCont.duration=duration;
                                                    console.log("响应消息："+JSON.stringify(retdata));
                                                    response.send(JSON.stringify(retdata));
                                                    return;
                                                }


                                            });
                                        }

                                    });



                                }

                            });
                        }
                        break;
                    default :

                }

            }catch(e){
                console.log("JSON格式不正确或不是JSON请求: "+JSON.stringify(info));
                response.redirect("login.html");
            }
            return;
        });




};
